package com.example.stars_project_android.index;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.stars_project_android.HelloActivity;
import com.example.stars_project_android.R;
import com.example.stars_project_android.entity.FlowLayout;
import com.example.stars_project_android.entity.MflowLayout;
import com.example.stars_project_android.entity.SpaceTime;
import com.example.stars_project_android.login.PsdLogin;
import com.example.stars_project_android.util.Constant;
import com.example.stars_project_android.util.KeyBoardUtil;
import com.example.stars_project_android.util.StorageListSPUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 搜索页面
 */
public class Search extends AppCompatActivity implements TextView.OnEditorActionListener, View.OnClickListener {

    private ImageButton back;    //返回按钮
    private ImageView delete;   //删除搜索框的内容
    private Button search, empty, change;   //搜索，清空，换一批
    //搜索输入框
    private EditText editText;
    //历史搜索的流式布局属性
    private FlowLayout flowLayout;
    //搜索发现的流式布局属性
    private MflowLayout mflowLayout;
    //搜索发现的数据集合
    private List<String> list = new ArrayList<>();
    // SharedPreferences 存取 搜索历史 的标签
    private static final String TAG_SEARCH_HISTORY = "tagSearchHistory";
    // 默认最多展示的搜索历史数
    // 这里只展示10个搜索历史，根据需要修改为你自己想要的数值
    private static final int DEFAULT_SEARCH_HISTORY_COUNT = 10;
    // 搜索历史
    private List<String> mSearchHistoryLists;
    // 存储 搜索历史集合 的工具类
    private StorageListSPUtils mStorageListSPUtils;
    private static final String TAG = Search.class.getSimpleName();
    //历史搜索的集合
    private List<TextView> serchHis = new ArrayList<>();
    //搜索发现的集合
    private List<TextView> serchFind = new ArrayList<>();
    private int code;   //返回的状态码
    private String msgCon;  //返回的信息
    //handler处理子线程的数据
    private Handler myHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //处理子线程发送的消息
            String result = (String) msg.obj;
            try {
                JSONObject jsonObject = new JSONObject(result);
                code = jsonObject.getInt("code");
                msgCon = jsonObject.getString("msg");
                Log.e("状态码",code+"");
                Log.e("返回的提示信息：",msgCon);
                if (code == 200) {
                    if (Constant.searchList.size() != 0){
                        Constant.searchList.clear();
                    }

                    JSONObject jsonObject1 = jsonObject.getJSONObject("date");
                    JSONArray jsonArray = jsonObject1.getJSONArray("content");
                    for (int i = 0; i < jsonArray.length(); i++){
                        JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                        SpaceTime spaceTime = new SpaceTime();
                        spaceTime.setRoomId(jsonObject2.getString("roomId"));
                        spaceTime.setCreateTime(jsonObject2.getString("createTime"));
                        spaceTime.setRoomName(jsonObject2.getString("roomName"));
                        spaceTime.setUserCountMax(jsonObject2.getInt("userCountMax"));
                        spaceTime.setUserCountCurrent(jsonObject2.getInt("userCountCurrent"));
                        spaceTime.setUserPhone(jsonObject2.getString("userPhone"));
                        spaceTime.setRoomDescribe(jsonObject2.getString("roomDescribe"));
                        spaceTime.setRoomAttribute(jsonObject2.getString("roomAttribute"));
                        spaceTime.setRoomState(jsonObject2.getString("roomState"));
                        Constant.searchList.add(spaceTime);
                    }
                    //跳转到搜索结果的页面
                    Intent intent = new Intent(Search.this, SearchReault.class);
                    intent.putExtra("search",editText.getText().toString());
                    startActivity(intent);
                } else {
                    //提示错误信息
                    Toast.makeText(Search.this,msgCon,Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        //绑定控件对象
        setView();
        // 初始化
        init();
        // 初始化搜索历史布局
        initView();

        //设置搜索的发现的数据源
        list.add("快乐");
        list.add("学");

        /**
         * 初始化搜索发现的布局
         */
        for (int i = 0; i < list.size(); i++) {
            View inflate = LayoutInflater.from(this).inflate(R.layout.layout_item, null);
            TextView label = inflate.findViewById(R.id.text);
            label.setText(list.get(i));
            mflowLayout.addView(inflate);
            serchFind.add(label);
            initEvent(serchFind);
        }

        /**
         * EditText添加监听
         */
        editText.addTextChangedListener(new TextWatcher() {
            //文本改变之前执行
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            //文本改变的时候执行
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //如果长度为0
                if (s.length() == 0) {
                    //隐藏“删除”图片
                    delete.setVisibility(View.GONE);
                } else {//长度不为0
                    //显示“删除图片”
                    delete.setVisibility(View.VISIBLE);
                }
            }
            //文本改变之后执行
            public void afterTextChanged(Editable s) { }
        });
    }

    /**
     * 初始化
     */
    private void init() {
        // 初始化搜索历史
        mSearchHistoryLists = new ArrayList<>();
        // 初始化存储 搜索历史集合 的工具类
        mStorageListSPUtils = new StorageListSPUtils(this, TAG);
        //设置历史数据
        mSearchHistoryLists.add("一个人");
        mSearchHistoryLists.add("我");
        mStorageListSPUtils.saveDataList(TAG_SEARCH_HISTORY,mSearchHistoryLists);

    }

    /**
     * 初始化搜索历史布局
     */
    private void initView() {
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        // 获取 SharedPreferences 中已存储的 搜索历史
        mSearchHistoryLists = mStorageListSPUtils.loadDataList(TAG_SEARCH_HISTORY);
        for (int i = 0; i < mSearchHistoryLists.size(); i++) {
            View inflate = layoutInflater.from(this).inflate(R.layout.layout_item, null);
            TextView label = inflate.findViewById(R.id.text);
            label.setText(mSearchHistoryLists.get(i));
            flowLayout.addView(inflate);
            serchHis.add(label);
            initEvent(serchHis);
        }

    }

    /**
     * 历史搜索和搜索发现的点击事件
     */
    private void initEvent(List<TextView> list) {
        for (int i = 0;i < list.size();i++){
            String str = (String) list.get(i).getText();
            list.get(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.e("点击了",str);
                    getConn(str);
                }
            });
        }
    }

    /**
     * 存取 SharedPreferences 中存储的搜索历史并做相应的处理
     */
    private void processAction() {
        // 获取 EditText 输入内容
        String searchInput = editText.getText().toString().trim();
        if (TextUtils.isEmpty(searchInput)) {
            Toast.makeText(this, getResources().getString(R.string.app_search_input_empty), Toast.LENGTH_SHORT).show();
        } else {
            // 先获取之前已经存储的搜索历史
            List<String> previousLists = mStorageListSPUtils.loadDataList(TAG_SEARCH_HISTORY);
            if (previousLists.size() != 0) {
                // 如果之前有搜索历史，则添加
                mSearchHistoryLists.clear();
                mSearchHistoryLists.addAll(previousLists);
                Log.e("数据长度",mSearchHistoryLists.size() + "");
            }
            // 去除重复，如果搜索历史中已经存在则remove，然后添加到后面
            if (!mSearchHistoryLists.contains(searchInput)) {
                // 如果搜索历史超过设定的默认个数，去掉最先添加的，并把新的添加到最后
                // 这里只展示10个搜索历史，可以根据需要修改为自己想要的数值
                if (mSearchHistoryLists.size() >= DEFAULT_SEARCH_HISTORY_COUNT) {
                    mSearchHistoryLists.remove(0);
                    mSearchHistoryLists.add(mSearchHistoryLists.size(), searchInput);
                } else {
                    mSearchHistoryLists.add(searchInput);
                }
            } else {
                // 如果搜索历史已存在，找到其所在的下标值
                int inputIndex = -1;
                for (int i = 0; i< mSearchHistoryLists.size(); i++) {
                    if (searchInput.equals(mSearchHistoryLists.get(i))) {
                        inputIndex = i;
                    }
                }
                // 如果搜索历史已存在，先从 List 集合中移除再添加到集合的最后
                mSearchHistoryLists.remove(inputIndex);
                mSearchHistoryLists.add(mSearchHistoryLists.size(), searchInput);
            }
            // 存储新的搜索历史到 SharedPreferences
            mStorageListSPUtils.saveDataList(TAG_SEARCH_HISTORY, mSearchHistoryLists);
            Toast.makeText(this, getResources().getString(R.string.app_search_input) + searchInput, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * EditText 编辑完成点击软键盘搜索后的监听事件
     */
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (v.getId() == R.id.edit) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                // 存取 SharedPreferences 中存储的搜索历史并做相应的处理
                processAction();
                // 点击软件盘搜索后，隐藏软键盘
                if (null != getCurrentFocus()) {
                    KeyBoardUtil.hideKeyboard(getCurrentFocus(), Search.this);
                }
                return true;
            }
        }
        return false;
    }

    /**
     * 绑定控件对象
     */
    private void setView() {
        flowLayout = findViewById(R.id.flowLayout);
        mflowLayout = findViewById(R.id.mflowLayout);
        back = findViewById(R.id.ib_concern_star_return);
        back.setOnClickListener(this);
        search = findViewById(R.id.btn_search);
        search.setOnClickListener(this);
        empty = findViewById(R.id.btn_empty);
        empty.setOnClickListener(this);
        change = findViewById(R.id.btn_change);
        change.setOnClickListener(this);
        editText = findViewById(R.id.edit);
        delete = findViewById(R.id.delete);
        delete.setOnClickListener(this);
    }

    /**
     * 点击事件
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ib_concern_star_return:
                //返回上一步
                this.finish();
                break;
            case R.id.delete:
                //设置删除图片的点击事件
                delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //把EditText内容设置为空
                        editText.setText("");
                    }
                });
                break;
            case R.id.btn_search:
                // 存取 SharedPreferences 中存储的搜索历史并做相应的处理
                processAction();
                //获取网络连接，传递数据
                getConn(editText.getText().toString());
                break;
            case R.id.btn_empty:
                // 删除搜索历史
                new AlertDialog.Builder(this)
                        .setMessage(getResources().getString(R.string.app_commit_delete_history))
                        .setCancelable(false)
                        .setPositiveButton(getResources().getString(R.string.app_delete_confirm), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 清除 SharedPreferences 中存储的搜索历史
                                mStorageListSPUtils.removeDateList(TAG_SEARCH_HISTORY);
                                mSearchHistoryLists.clear();
                                flowLayout.removeAllViews();
                                // 删除之后，搜索历史布局隐藏
                                flowLayout.setVisibility(View.GONE);
                            }
                        })
                        .setNegativeButton(getResources().getString(R.string.app_delete_cancel), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();
                break;
            case R.id.btn_change:
                //点击换一批

                break;
            default:
                break;
        }
    }

    /**
     * 获取网络连接
     */
    private void getConn(String msg) {
        //向后端传递页面上获取的搜索信息
        //将数据封装
//        JSONObject jsonObject = new JSONObject();
//        try {
//            jsonObject.put("search",editText.getText().toString());
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        Log.e("search",editText.getText().toString());
//        Log.e("json格式",jsonObject.toString());

        OkHttpClient okHttpClient = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("http://192.168.1.7:8080/room/findRoomByName?roomName="+msg)
                    .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("okhttp","请求成功");
                //处理后端的数据
                response = okHttpClient.newCall(request).execute();
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }
}